<?php
namespace app\services\admin;

use app\helper\tools\Security;
use app\models\User;

class ManageService
{
    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function getManager($id)
    {
        $res = $this->user->with('roles')->where('id', $id)->find();

        if ($res) {
            $result = $res->hidden(['password', 'lock_version'])->toArray();
            $roles = $res->roles()->where('user_id', $res->id)->select();
            if (! $roles->isEmpty()) {
                $roles->each(function ($item) use (& $result) {
                    $result['role'][] = $item->id;
                });
            } else {
                $result['role'] = '';
            }
            $result['status'] = $res->getData('status');
            return $result;
        }
        return [];
    }

    public function getManagerList($status, $search, $size = 15)
    {
        $res = $this->user
            ->with('roles')
            ->withSearch(['name', 'status'], ['name' => $search, 'status' => $status])
            ->order('id', 'desc')
            ->paginate($size);
        if ($res) {
            $pageInfo = $res->toArray();
            /** 由于vue 中要int类型，框架输出的current_page是字符串类型，造成导航页码循环有问题 */
            $pageInfo['current_page'] = intval($pageInfo['current_page']);
            return $pageInfo;
        }

        return [];
    }

    public function saveManager($data)
    {
        $res = $this->user
            ->withSearch(['email'], ['email' => $data['email']])
            ->find();

        if ($res) {
            return [false, '已存在邮箱'];
        }

        $data['password'] = Security::encrypt($data['password'], config('security.app_key'));

        if ($this->user->allowField(['name', 'email', 'password', 'status'])->save($data)) {
            $this->user->roles()->save($data['role']); //写入关联表
            return [true, '保存完成'];
        }
        return [false, '未知错误'];
    }

    public function saveModifyManager($data)
    {
        $res = $this->user->with('roles')->find($data['id']);

        if ($res) {
            $res->name = $data['name'];
            $res->status = $data['status'];

            /** 删除原来的关联，重新保存新的 */
            $res->roles()->where('user_id', $res->id)->detach();
            $res->roles()->save($data['role']);

            if ($res->force()->save()) { //无论数据是否有变化，强制更新
                return [true, '保存完成'];
            }
        }
        return [false, '未知错误'];
    }

    public function delManager($id)
    {
        $user = $this->user->where('id', $id)->find();
        $user->roles()->where('user_id', $id)->detach();
        if ($user->delete()) {
            return true;
        }

        return false;
    }

    public function modifyPassword($data)
    {
        $plain = $data['old_password'] ?? '';
        $newPassword = $data['password'] ?? '';

        $user = $this->user->where('id', session('admin_login_id'))->find();

        if (! $user) {
            return [false, '无效用户'];
        }

        $userPass = Security::decrypt($user->password, config('security.app_key'));

        if ($plain !== $userPass) {
            return [false, '旧密码不正确'];
        }

        $user->password = Security::encrypt($newPassword, config('security.app_key'));
        if ($user->save()) {
            return [true, '修改成功'];
        }
        return [false, '未知错误，请重试'];
    }
}
